<template>
<!-- 验证码组件 -->
  <div class="codes">
    <canvas
      id="canvas"
      width="120"
      height="30"
      @click="draw()"
      v-if="cavasShow"
    ></canvas>
  </div>
</template>

<script>


export default {
  data() {
    return {
      // 画布上下文
      cxt: "",
      //   四位验证码
      codearr: [],
      //   随机数
      codeData: "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ0123456789",
      //   画布的展示与否
      cavasShow: true,
      // 发射给父组件得四位验证码
      
    };
  },
  methods: {
    draw() {
      if (this.cavasShow) {
        this.codearr = [];
        //   绘制一个颜色随机的矩形
        this.cxt.beginPath();
        this.cxt.fillStyle = this.randColor(170, 250); //把颜色放到一个方法
        this.cxt.fillRect(0, 0, 120, 30);
        this.cxt.closePath();

        for (let i = 0; i <= 90; i += 30) {
          //四位验证码
          var c = this.codeData[this.randNum(0, this.codeData.length - 1)];
          // 生成四位验证码
          this.codearr.push(c);
          this.cxt.beginPath();
          this.cxt.fillStyle = this.randColor(60, 160);
          this.cxt.font = this.randNum(20, 40) + "px SimHei";
          this.cxt.fillText(c, i + this.randNum(0, 15), this.randNum(15, 30)); //[0,15) [30,45) [60,75) [90,115)
          this.cxt.closePath();
        }
        //渲染干扰线
        for (let j = 0; j < 10; j++) {
          this.cxt.beginPath();
          this.cxt.moveTo(this.randNum(0, 120), this.randNum(0, 120)); //这里的randNum(min,max)与canvas的画板宽高相联系，
          this.cxt.lineTo(this.randNum(0, 120), this.randNum(0, 120));
          this.cxt.strokeStyle = this.randColor(60, 120);
          this.cxt.stroke();
        }
        for (let i = 0; i < 10; i++) {
          this.cxt.beginPath();
          this.cxt.strokeStyle = this.randColor(50, 130);
          this.cxt.arc(
            this.randNum(0, 120),
            this.randNum(0, 30),
            this.randNum(1, 3),
            0,
            2 * Math.PI
          );
          this.cxt.stroke();
          this.cxt.closePath();
        }
        // 最后的四位验证码结果
        // console.log(this.codearr, "最后的四位验证码");
        // 发射给父组件
       this.$emit('childByValue', this.codearr)
        
      }
    },
    randColor(min, max) {
      //max+1是取不到的，但是max是可以取到的，所以向下取整刚好取到[min,max]。
      var r = Math.floor(Math.random() * (max - min + 1) + min); //Math.random * （max- min)==>[o,min)变成[min,max-min]的范围
      var g = Math.floor(Math.random() * (max - min + 1) + min);
      var b = Math.floor(Math.random() * (max - min + 1) + min);
      return "rgb(" + r + "," + g + "," + b + ")";
    },

    randNum(min, max) {
      var num = Math.floor(Math.random() * (max - min + 1) + min);
      return num;
    },
  },

  mounted() {
    var canvas = document.querySelector("#canvas");
    if (this.cavasShow) {
      this.cxt = canvas.getContext("2d"); //绘图上下文环境
    }

    this.draw();
  },
};
</script>

<style lang="less"  scoped>
#canvas {
  cursor: pointer;
  /*border: 1px solid red;*/
}
</style>

